<?php

/*------------------------------------------------
*
*   Explay Engine Content Management System.
*   Copyright © 2008 Golovdinov Alexander.
*
*-------------------------------------------------
*
*   Official site: wwww.alex-home.spb.ru/explay.html
*   Contact e-mail: golovdinov@gmail.com
*
*   GNU General Public License original source:
*   http://www.gnu.org/licenses/gpl-3.0.html
*
------------------------------------------------*/

if (!defined ('EXPLAY')) exit;

class articlesView {
	
	private $SITE;
	
	public function __construct () {
		$this->SITE = CORE::$SITE;
	}
	
	/**
	 * Вывод статьи из списка
	 */
	public function display_item ($article1, $i) {
		
		$model = articlesModel::getInstance();
		
		$article = $article1;

		$return = '';

		// Если выбрана категория статей, выводим информацию о облоге
		if ($i == 1 && isset($_GET['cat']) && $_GET['cat'] != 'all'  && $_GET['cat'] != 'articles' && $_GET['cat'] != 'comments' && count(articlesModel::$search_words) == 0) {
	
			CORE::set_page_title ($article['cat_header'].' / {module_header} &mdash; '.$this->SITE['site_name']);
	
			$return .= $this->show_blog_info (
								$article['cat_id'],
								$article['art_category'],
								$article['cat_header'],
								$article['cat_description'],
								$article['cat_voters'],
								$article['cat_rating']
						);
		}

		// Если выбраны статьи пользователя, выводим вторичное меню
		if ($i == 1 && !empty($model->author) && count(articlesModel::$search_words) == 0) {
			past_navblock (array (
					array ("Профиль $user_name", "/users/$author.html", 'name', 'users'),
					array ("Публикации $user_name", "/articles/?user=$author", 'user', $author)
							)
			);
		}

		// Подсветка поисковых слов
		if (count(articlesModel::$search_words) > 0) {
			foreach (articlesModel::$search_words as $word) {
				$word = mb_strtolower (trim ($word));

				$article['art_header'] = preg_replace ("/$word/iu", "<span style=\"background-color:yellow;\">$word</span>", $article['art_header']);
				$article['art_body'] = preg_replace ("/$word/iu", "<span style=\"background-color:yellow;\">$word</span>", $article['art_body']);
			}
		}

		if ($artilce['cnt_com'] == '') $artilce['cnt_com'] = 0;

		if ($article['auto_tag'] == 'yes') $article['art_body'] = n2br ($article['art_body']);

		$body = explode ('<cut>', $article['art_body']);
		($body[1] != '')
			? $article['art_body'] = $body[0]."<br /><a href=\"/articles/".$article['art_id'].".html\">читать дальше &rarr;</a>"
			: $article['art_body'] = $body[0];

		$article['art_rating'] = $this->print_rating ($article['art_id'], $article['art_rating'], $article['art_voters'], $article['art_author']);
		$article['art_body'] = input_video (replace_symbols ($article['art_body']));
		$article['art_body'] = preg_replace ("#(?<![\'|\"])http:\/\/(.+?)(?![\'|\"])[^\s|\)|<]{0,}#", "<a href=\"\\0\">\\0</a>", $article['art_body']);
		$article['art_date'] = format_time($article['art_date']);
		$article['comments'] = count_smth ($article['cnt_com'], array ('комментарий', 'комментария', 'комментариев'));
		$article['art_tags'] = $this->print_tags ($article['art_tags']);


		(file_exists ($article['art_image']))
			? $article['art_image'] = "<a href=\"/$image\" target=\"_blank\"><img src=\"/thumbs.php?x=160&y=160&url=$image\" align=\"left\" alt=\"$header\"></a>"
			: $article['art_image'] = '';
			
		($article['art_visible'] == 'off')
			? $article['art_visible'] = Templater::display_part ('invisible', false)
			: $article['art_visible'] = '';

		Templater::$user_id = User::$properties['user_id'];
		Templater::$author_id = $article['art_author'];
		
		Templater::set_var ('article', $article);
		
		((is_admin() || is_moderator()) && $article['art_publik'] == 'no')
			? Templater::set_var ('moderate', Templater::display_part ('moderate', false))
			: Templater::set_var ('moderate', '');
		
		// Если категория равна 0, то парсим шаблон для персонального блога
		$return .= (mb_strlen ($article['art_category'])) ? Templater::display_part ('public_blog') : Templater::display_part ('personal_blog');
		
		Templater::unset_vars ('article');
		unset ($article, $model);
			
		return $return;

	}
	
	/**
	 * Вывод полной статьи
	 */
	public function display_article ($article) {
		
		$model = articlesModel::getInstance();
		
		if ($article['auto_tag'] == 'yes') $article['art_body'] = n2br($article['art_body']);
		$article['art_body'] = input_video (replace_symbols ($article['art_body']));
		
		// Создаем ключевые слова для страницы из тегов статьи
		if ($article['art_tags'] != '') {
			$tagline = '';
			$tags = trim ($article['art_tags']);
			if (substr($tags, mb_strlen($tags)-1) == ',') $tags = substr($tags, 0, mb_strlen($tags)-1);
			$tags = explode (',', $tags);
			
			for ($i=0; $i<count($tags); $i++) {
				$tagline .= trim($tags[$i]);
			
				if ($i+1 != count($tags)) $tagline .= ', ';
			}
			//$CORE->SITE['site_keywords'] = $tagline;
			CORE::set_keywords ($tagline);
		}
				
		// Если статья статичная
		if ($article['art_like_page'] == 'yes') {
			past_table ($article['art_header'], $article['art_body']);
			
			CORE::set_page_title ($article['art_header'].' &mdash; '.$this->SITE['site_name']);
		
		// Обычная статья
		} else {
			
			Templater::load ('articles/list_view.tpl');
						
			// Устанавливаем заголовок
			($article['art_category'] != '')
				? CORE::set_page_title ($article['art_header'].' / '.$article['cat_header'].' &mdash; {module_header} &mdash; '.$this->SITE['site_name'])
				: CORE::set_page_title ($article['art_header'].' / персональный блог '.$article['user_name'].' &mdash; '.$this->SITE['site_name']);
			
			$blog_info ='';
			
			// Информация о блоге
			if ($article['art_category'] != '') {
				$blog_info = $this->show_blog_info (
								$article['cat_id'],
								$article['art_category'],
								$article['cat_header'],
								$article['cat_description'],
								$article['cat_voters'],
								$article['cat_rating']
						);
			}
			
			// Past article
			$article['art_rating'] = $this->print_rating ($article['art_id'], $article['art_rating'], $article['art_voters'], $article['art_author']);
			$article['art_body'] = input_video (replace_symbols ($article['art_body']));
			$article['art_body'] = preg_replace ("#(?<![\'|\"])http:\/\/(.+?)(?![\'|\"])[^\s|\)|<]{0,}#", "<a href=\"\\0\">\\0</a>", $article['art_body']);
			$article['art_date'] = format_time($article['art_date']);
			$article['art_tags'] = $this->print_tags ($article['art_tags']);
	

			(file_exists ($article['art_image']))
				? $article['art_image'] = "<a href=\"/$image\" target=\"_blank\"><img src=\"/thumbs.php?x=160&y=160&url=$image\" align=\"left\" alt=\"$header\"></a>"
				: $article['art_image'] = '';
				
			($article['art_visible'] == 'off')
				? $article['art_visible'] = Templater::display_part ('invisible', false)
				: $article['art_visible'] = '';
	
			Templater::$user_id = User::$properties['user_id'];
			Templater::$author_id = $article['art_author'];
			
			Templater::set_var ('article', $article);
			Templater::set_var ('blog_info', $blog_info);
			
			((is_admin() || is_moderator()) && $article['art_publik'] == 'no')
				? Templater::set_var ('moderate', Templater::display_part ('moderate', false))
				: Templater::set_var ('moderate', '');
			
			// Если категория равна 0, то парсим шаблон для персонального блога
			return (mb_strlen ($article['art_category']))
				? Templater::display ('articles/article_view.tpl')
				: Templater::display ('articles/article_view.tpl');
			
			Templater::unset_vars ('article');
			unset ($article);
		}
		
		unset ($model);
	
	}
	
	/**
	 * Вывод информации о блоге
	 */
	private function show_blog_info ($id, $name, $header, $desc, $voters, $rating) {
		
		$model = articlesModel::getInstance();
		$mysql = articlesMySQL::getInstance();
		
		$blog = array ();
		Templater::load ('articles/blog_info.tpl', false);
		
		// Подсчитываем количество "читателей"
		$blog['cnt_users'] = $mysql->count_users_in_blog ($id);

		// Ставим опции блога (присоедениться или выйти)
		Templater::set_var ('id', $id);
		if (is_registered()) {
			($model->in_blog($id))
				? $blog['options'] = Templater::display_part ('blog_info_exit')
				: $blog['options'] = Templater::display_part ('blog_info_join');
		}
		else $blog['options'] = '';


		Templater::set_var ('rating', number_format ($rating, 2, ',', ''));
		Templater::set_var ('name', $name);
		
		(!is_registered() || my_karma() < 0 || $model->is_voted_blog ($voters))
			? $blog['karma'] = Templater::display_part ('blog_info_karma_cant', false)
			: $blog['karma'] = Templater::display_part ('blog_info_karma_good', false);
				
		(file_exists ($_SERVER['DOCUMENT_ROOT']."/images/blogs/$name.jpg"))
			? $blog['avatar_src'] = "/images/blogs/$name.jpg"
			: $blog['avatar_src'] = '/images/noavatar.gif';
		
		$blog['name'] = $name;
		$blog['description'] = $desc;
		$blog['header'] = $header;
		$blog['id'] = $id;
		
		Templater::set_var ('blog', $blog);
					
		return Templater::display_part ('blog_info_main');	
		
		unset ($model, $mysql);
	}

	/**
	 * Вывод строки с ссылками на теги
	 */
	public function print_tags ($tags) {
		$tagline = '';
		$tags = trim ($tags);
		if (substr($tags, mb_strlen($tags)-1) == ",") $tags = substr($tags, 0, mb_strlen($tags)-1);
		$tags = explode (',', $tags);

		for ($i=0; $i<count($tags); $i++) {
			$tagline .= '<a href="/articles/?tagname='.urlencode(trim($tags[$i])).'" title="'.trim($tags[$i]).'">'.trim($tags[$i]).'</a>';

			if ($i+1 != count($tags)) $tagline .= ', ';
		}
		return $tagline;
	}

	/**
	 * Вывод оценки
	 */
	public function print_rating ($id, $rating, $voters, $author) {
		$vote = false;
		$voters = explode (',', $voters);
		
		foreach ($voters as $v) if (User::$properties['user_id'] == trim($v)) $vote = true;

		($rating == 0) ? $rating = '0 баллов' : $rating = count_smth ($rating, array ('балл', 'балла', 'баллов'));
		
		Templater::set_var('id', $id);
		Templater::set_var('rating', $rating);
		
		if (is_registered () && my_karma() >= 0 && User::$properties['user_id'] != $author && $vote == false)
			$rating_tpl = Templater::display_part ('change_rating', false);
		else
			$rating_tpl = Templater::display_part ('cant_rating', false);
		
		Templater::unset_vars ('id', 'rating');
		
		return $rating_tpl;
	}
	
	/**
	 * Полоска "одобренные/все" (бар)
	 */
	public function past_bar ($blog, $user) {
		
		if ($blog == '' && !isset($_GET['tagname']) && !isset($_GET['searcfor']) && $user == 0)
			return (isset($_GET['cat']) && $_GET['cat'] == 'all')
				? Templater::display ('articles/bar_all.tpl', false)
				: Templater::display ('articles/bar_mainpage.tpl', false);
	}
	
	/**
	 * Форма поиска
	 */
	public function search_form ($text) {
		Templater::load ('articles/forms.tpl');
		Templater::set_var ('text', $text);
		return Templater::display_part ('search');
	}
	
	/**
	 * Форма тегов
	 */
	public function tags_form ($tags) {
		Templater::load ('articles/forms.tpl');
		Templater::set_var ('tags', $tags);
		return Templater::display_part ('tags');
	}
	
}